package com.orangelife.mobile.parkingcard.activity;

/**
 * 停车管理--有停车卡时
 */

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.adapter.HaveCardListAdapter;
import com.orangelife.mobile.parkingcard.adapter.HaveCardListAdapter.OnLongClickListenerInterface;
import com.orangelife.mobile.parkingcard.biz.ParkingCardHttpBiz;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HaveCardListActivity extends OrangeLifeBaseActivity implements OnLongClickListenerInterface {

    /**
     * 标题
     */
    private TextView tvTitle;

    /**
     * 停车卡列表
     */
    private PullToRefreshListView lvList;

    /**
     * 添加停车卡
     */
    private Button btnAddParkingCard;

    /** 数据list */
    private List<Map<String, Object>> list = null;
    private List<Map<String, Object>> list2;

    /** 分辨是刷新还是加载更多 */
    private int flags = 1;
    /** 一页中数据的条数，初始设置为7条 */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /** 初始页，初始化为第一页 */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private Handler mHandler;

    /** 停车卡ID */
    private String parkingCardID = "";
    /** 车牌号 */
    private String carNumber = "";
    /** 进度条的dialog */
    private Dialog dialog = null;
    /** 数据的adapter */
    @SuppressWarnings("rawtypes")
    private HaveCardListAdapter adapter = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_havecard);
        initeView();
        findView();
    }

    /**
     * 初始化
     */
    private void initeView() {

        tvTitle = (TextView) findViewById(R.id.tv_title);
        btnAddParkingCard = (Button) findViewById(R.id.btnSubmit);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dialog = DialogHelper.getInstance().createLoadingDialog(this, Constant.LOADING);
        dialog.show();
        pageNo = 1;
        flags = 1;
        getParkingCard(pageSize, pageNo);
    }

    /**
     * 赋值
     */
    private void findView() {

        tvTitle.setText(R.string.parking_manage);
        mHandler = new Handler();
        setAdapter();
        pullListView();
        btnAddParkingCard.setOnClickListener(listener);
        lvList.setOnItemLongClickListener(longListener);

    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvList.setXListViewListener(new IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvList.stopRefresh();
        lvList.stopLoadMore();
        lvList.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    @SuppressWarnings({"unchecked"})
    private void updateListView(List<Map<String, Object>> list2) {

        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        } else {
            lvList.setPullLoadEnable(false);
        }
    }

    /**
     * 为listview设置值
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void setAdapter() {

        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new HaveCardListAdapter(HaveCardListActivity.this, list, this);
        lvList.setAdapter(adapter);
    }

    /**
     * 点击事件的监听器
     */
    public OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btnSubmit:
                    IntentHelper.getInstances().getIntent(HaveCardListActivity.this, ApplyForParkingCardBeginActivity.class);
                    break;

                default:
                    break;
            }
        }
    };

    public OnItemLongClickListener longListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {

            parkingCardID = list.get(position - 1).get("id").toString();
            carNumber = list.get(position - 1).get("num_plate").toString();
            String status = list.get(position - 1).get("status").toString();
            if ("0".equals(status)) {
                isDeleteDialog();
            }
            return true;
        }
    };

    /** 弹出对话框 */
    private void isDeleteDialog() {
        String message = "确定要删除" + carNumber + "吗？";
        final ConfirmDialog confirmDialog = new ConfirmDialog(
                HaveCardListActivity.this, getResources().getString(
                R.string.warm_prompt), message, getResources().getString(
                R.string.cancel), getResources().getString(
                R.string.sure));
        confirmDialog.show();
        confirmDialog
                .setClicklistener(new ConfirmDialog.ClickListenerInterface() {

                    @Override
                    public void doLeft() {
                        confirmDialog.dismiss();
                    }

                    @Override
                    public void doRight() {
                        confirmDialog.dismiss();
                        deleteParkingCard();

                    }
                });
    }

    /**
     * 删除消息
     */
//	@SuppressWarnings("deprecation")
//	private void deleteParkingCard() {
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("{cardID}", parkingCardID);
//		Map<String, Object> rootMap = new HashMap<String, Object>();
//		rootMap.put("map", map);
//		rootMap.put("url", Constant.URL_PARKCARD_DELETE);
//		rootMap.put("wat", 1);
//		new JSONRequest(JSONRequest.DELETE, rootMap, handler,
//				HttpUtil.ACTION_JSON);
//	}
    @SuppressWarnings("deprecation")
    private void deleteParkingCard() {
        ParkingCardHttpBiz.delPakingCard(parkingCardID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    pageNo = 1;
                    flags = 1;
                    getParkingCard(pageSize, pageNo);
                    onLoad();
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    ToastHelper.getInstance()._toast("删除成功");
                } else {
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast("删除失败");
                }
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void getParkingCard(int pageSize, int pageNo) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("pageSize", String.valueOf(pageSize));
        map.put("pageIndex", String.valueOf(pageNo));
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_LIST, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                list2 = OrangeDataHandler.getListFromJsonWithPageEntity(
                        jsonObject, new TypeToken<List<Map<String, Object>>>() {
                        }.getType(), adapter, dialog);
                updateListView(list2);
            }
        });
    }


    /**
     * 处理获得的数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(list2);
                    break;
                case 1:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        dialog.show();
                        pageNo = 1;
                        flags = 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                        ToastHelper.getInstance()._toast("删除成功");
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast("删除失败");
                    }
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;

                default:
                    break;
            }
        }

    };


    @Override
    public void delete(int position, Map<String, Object> map) {

//		parkingCardID = list.get(position).get("id").toString();
//		carNumber = list.get(position).get("num_plate").toString();
//		String status = list.get(position).get("status").toString();
//		if("0".equals(status)){
//			isDeleteDialog();
//		}

    }

}
